﻿# -*- coding: utf-8 -*-
import datetime
from django.db import models
from django.contrib.markup.templatetags import markup

from django.conf import settings
from biologeek.tagging.models import Tag
from biologeek.tagging.fields import TagField

#TODO: deal with wiki2xhtml markup

class PostManager(models.Manager):
    def get_query_set(self):
        """ Retrieve only published posts. """
        qs = super(PostManager, self).get_query_set()
        return qs.filter(is_online=True, publication_date__lte=datetime.datetime.now())

    def get_best_of(self):
        """ Retrieve only best of published posts. """
        qs = super(PostManager, self).get_query_set()
        return qs.filter(is_bestof=True, publication_date__lte=datetime.datetime.now())


MARKUP_CHOICES = (
    ('markdown', 'Markdown'),
    ('textile', 'Textile'),
    ('restructuredtext', 'ReST'),
    ('wiki2xhtml', 'Dotclear'),
)

def wiki2xhtml(content):
    return content

markup.wiki2xhtml = wiki2xhtml

class Post(models.Model):
    title = models.CharField('Titre', maxlength=200)
    slug = models.SlugField('Adresse', prepopulate_from=('title',))
    tags = TagField(help_text='Écrivez vos tags, séparés par des espaces ou des virgules.')

    summary = models.TextField('Description', help_text='Différentes syntaxes possibles (cf. markup)', blank=True)
    summary_html = models.TextField('Description HTML', blank=True)
    content = models.TextField('Contenu', help_text='Difféntes syntaxes possibles (cf. markup)')
    content_html = models.TextField('Contenu HTML', blank=True)

    related_posts = models.ManyToManyField('self', help_text='Sélectionnez les billets en relation.', blank=True)
    related = models.TextField('Contenu additionnel', help_text='Difféntes syntaxes possibles (cf. markup)', blank=True)
    related_html = models.TextField('Contenu additionnel HTML', blank=True)

    creation_date = models.DateTimeField('Date de création', null=True, blank=True)
    modification_date = models.DateTimeField('Date de modification', null=True, blank=True)
    publication_date = models.DateTimeField('Date de publication', null=True, blank=True)

    image = models.ImageField('Image associée', upload_to='%slogos/' % settings.MEDIA_ROOT, blank=True)
    is_online = models.BooleanField('En ligne', default=False)
    is_bestof = models.BooleanField('Best of', default=False)
    markup = models.CharField(maxlength=16, choices=MARKUP_CHOICES, radio_admin=True, default='markdown')

    class Admin:
        list_display = ('title', 'thumbnail', 'summary', 'is_online', 'creation_date')
        list_filter = ('modification_date', 'is_online')
        search_fields = ('title', 'content', 'summary')
        date_hierarchy = 'publication_date'

    class Meta:
        ordering = ['-publication_date']

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return "/%s/%s/" % (','.join([tag for tag in self.tags.split()]), self.slug)

    def save(self):
        if not self.id:
            self.creation_date = datetime.datetime.now()
        else:
            self.modification_date = datetime.datetime.now()
        if not self.publication_date:
            self.publication_date = self.modification_date
        if self.markup != 'wiki2xhtml':
            syntax_converter = getattr(markup, self.markup)
            self.summary_html = syntax_converter(self.summary)
            self.content_html = syntax_converter(self.content)
            self.related_html = syntax_converter(self.related)
        super(Post, self).save()

    def thumbnail(self):
        url = '/media/%s' % (self.get_image_url())
        return '<img src="%s" width="%s" height="%s"/>' % (url, 150, 75)

    thumbnail.short_description = 'Logo'
    thumbnail.allow_tags = True

    objects = models.Manager()
    published = PostManager()

